# -*- coding:utf-8 -*-
import xlrd
import datetime
from django.db import transaction

from apis.base_data.serializers import ImportProjectSerializer


class ImportServer:
    NOW_TIME = datetime.datetime.now()

    def __init__(self):
        self.sheet = None
        # self.template_type = template_type
        self.template_type_data = dict()
        self.select_fields = dict()

    def __get_import_sheet(self, path):
        workbook = xlrd.open_workbook(path)
        return workbook.sheets()[0]

    def __get_sheet_value(self, row, col):
        """ 获取单元格数据
        :param row: 第几行
        :param col: 第几列
        :return:
        """
        value = self.sheet.cell(row, col).value
        if type(value) == float:
            return str(value).replace('.0', '')
        return str(self.sheet.cell(row, col).value).strip()

    def get_import_rows_data(self, file_path, start_row=1):
        """ 获取excel数据
        :param file_path: 文件地址
        :param start_row: 从第几行开始取数据
        :return:
        """
        self.sheet = self.__get_import_sheet(file_path)
        rows_data = []
        for row in range(start_row, self.sheet.nrows):
            # python3.6以后字典有序，这里按列顺序取值
            is_valid = False
            row_data = dict()
            for col, key in enumerate(self.template_type_data['import_key']):
                value = self.__get_sheet_value(row, col)
                field = self.select_fields[key]['field'].split('.')[-1]
                row_data[field] = value
                if value:
                    is_valid = True
            # 如果每个字段值都为空，认为是无效数据
            if is_valid:
                rows_data.append(row_data)
        return rows_data

    def get_error_str(self, errors):
        """拼接错误信息字符串"""
        result = ''
        for v in errors:
            if not result:
                result += v[0]
            else:
                result += ';{}'.format(v[0])
        return result

    # def export_import_errors(self, error_data, file_name, first_line):
    #     """错误信息写入excel"""
    #     converted_date = datetime.datetime.today().strftime('%Y%m%d')
    #     file_dir = os.path.join('static/download/{}/'.format(converted_date))
    #     if not os.path.exists(file_dir):
    #         os.makedirs(file_dir)
    #     file_path = os.path.join(file_dir, '{0}_{1}'.format(uuid.uuid4(), file_name))
    #     template_type_name = get_dictionary_kv('template_type').get(self.template_type)
    #     wb = xlsxwriter.Workbook(file_path)
    #     sheet = wb.add_worksheet(template_type_name)
    #
    #     # 写入表头，增加1列错误信息
    #     sheet.write_row(0, 0, first_line + ['错误信息'])
    #     # 写入数据
    #     for raw, raw_data in enumerate(error_data):
    #         sheet.write_row(raw + 1, 0, raw_data.values())
    #     wb.close()
    #     return file_path


class ProjectImportServer(ImportServer):

    def __init__(self):
        super(ProjectImportServer).__init__()
        self.select_fields = {
            'dept_id': {'value': '县区', 'dict': '', 'field': 'dept_id'},
            'name': {'value': '项目名称', 'dict': '', 'field': 'name'},
            'price': {'value': '商机规模（万元）', 'dict': '', 'field': 'price'},
            'jf_name': {'value': '单位名称', 'dict': '', 'field': 'jf_name'},
            'creator_id': {'value': '项目跟进人', 'dict': '', 'field': 'creator_id'},
            'important_level': {'value': '项目级别（红、黄、绿）', 'dict': 'project_level', 'field': 'important_level'},
            'priority_level': {'value': '项目类型', 'dict': 'priority_level', 'field': 'priority_level'}
        }
        self.template_type_data = {
            'import_key': ['dept_id', 'name', 'price', 'jf_name', 'creator_id', 'important_level', 'priority_level'],
            'import_serializer': ImportProjectSerializer
        }


# 上传
def template_import(server, import_path, creator_id):
    success_line = 0
    error_rows = []
    # 获取文件数据
    rows = server.get_import_rows_data(import_path)
    # 处理数据
    row_data = ''
    try:
        with transaction.atomic():
            for row in rows:
                # 校验数据
                serializer_class = server.template_type_data.get('import_serializer')
                serializer = serializer_class(data=row, context={'creator_id': creator_id})
                if serializer.is_valid():
                    # 写入数据
                    row_data = serializer.data
                    serializer.save()
                    success_line += 1
                else:
                    # 记录错误数据
                    row['error'] = server.get_error_str(serializer.errors.values())
                    error_rows.append(row)
    except Exception as e:
        import traceback
        print(traceback.format_exc())
        print(row_data)
        return 0, '请联系管理员'
    return success_line, error_rows
